from flask import render_template,request,jsonify
from . import main
from .. import fun
from .. import db
from ..models import Article, Ifgapi
from ..models import Arttype
from ..models import Release
from app.myclass.dedecms import dedecms
import requests
import json
import time
import datetime
import re
from app.myclass.wyc import Wyc
from app.myclass.ifagou import ifagou
from app.myclass.addcount import Addcount
from app.models import Addcountdb


resession = requests.session()
ALLOWED_EXTENSIONS = {'txt'}

@main.route('/article',endpoint='article')
@fun.is_login
def article():
  page = request.args.get('page', 1, type=int)
  field = request.args.get('field', '', type=str)
  order = request.args.get('order', '', type=str)
  typeid = request.args.get('typeid', 0, type=int)
  status = request.args.get('status', 0, type=int)
  status_ifg = request.args.get('status_ifg', 0, type=int)
  vue = request.args.get('vue', 0, type=int)
  kw = request.args.get('kw', '', type=str)
  pagesize = request.args.get('pagesize', 20, type=int)
  descset = {}
  where = []
  if kw:
    where.append(Article.title.like("%{}%".format(kw.strip())))
  if typeid:
    where.append(Article.typeid==typeid)
  if status:
    where.append(Article.status==status)
  if status_ifg:
    status_ifg1=status_ifg
    if status_ifg<0:status_ifg1=0
    where.append(Article.status_ifg==status_ifg1)
  if field in ['addtime','updatetime'] and  order in ['desc','asc']:
    myorder = eval("Article.{}.{}()".format(field,order))
    descset['field']=field
    descset['order']=order
  else:
    myorder = Article.addtime.desc()
  category = Arttype.query.all()
  sitelistdata = []
  sitelist = db.session.query(Release,Release.id,Release.sitename,Release.url,Release.adddate).all()
  addcount = Addcount()
  for i in sitelist:
    count = addcount.get(i.id,i.adddate)
    tem = {'id':i.id,'sitename':i.sitename,'url':i.url,'count':count}
    sitelistdata.append(tem)
  db.session.close()
  article_list = Article.query.filter(*where).join(Arttype, Article.typeid==Arttype.id,isouter=True).order_by(myorder).paginate(page, per_page=pagesize,error_out=False)
  count = Article.query.filter(*where).count()
  data = enumerate(article_list.items)
  pagination = article_list
  if vue == 1:
    myjson = []
    for i in article_list.items:
      myjson.append(i.to_json())
    return json.dumps(myjson)
  else:
    return render_template('article/article_list.html',data=data,count=count,pagination=pagination,kw=kw.strip(),descset=descset,category=category,typeid=typeid,status=status,status_ifg=status_ifg,sitelist=sitelistdata,pagesize=pagesize)


@main.route('/article_vue',endpoint='article_vue')
@fun.is_login
def article_vue():
  return render_template('article/article_list_vue.html')



@main.route('/article_info/<id>',endpoint='article_info')
@fun.is_login
def article_info(id):
  article_data = Article.query.filter_by(id=id).first()
  return render_template('article/article_info.html',data=article_data)

@main.route('/article_add',endpoint='article_add',methods=['GET', 'POST'])
@fun.is_login
def article_add():
  if request.method == 'GET':
    db.create_all()
    category = Arttype.query.all()
    return render_template('article/article_add.html',category=category)
  elif request.method == 'POST':
    title = request.form.get('title', '', type=str)
    typeid = request.form.get('typeid', '', type=int)
    url = request.form.get('url', '', type=str)
    content = request.form.get('content', '', type=str)
    article_db = Article(title = title,typeid = typeid,url = url,content=content)
    res = db.session.add(article_db)
    db.session.commit()
    db.session.close()
    return fun.msg_json(1, '添加成功')

@main.route('/article_edit/<id>',endpoint='article_edit',methods=['GET','POST'])
@fun.is_login
def article_edit(id):
  if id:
    row = Article.query.filter_by(id=id).first()
    if row:
      if request.method == 'GET':
        return render_template('article/article_edit.html',row=row)
      elif request.method == 'POST':
        row.title = request.form.get('title', '', type=str)
        typeid = request.form.get('typeid', 0, type=int)
        if typeid:
            row.typeid = typeid
        row.url = request.form.get('url', '', type=str)
        row.content = request.form.get('content', '', type=str)
        db.session.commit()
        db.session.close()
        return fun.msg_json(1, '修改成功')

@main.route('/article_del',endpoint='article_del',methods=['GET','POST'])
@fun.is_login
def article_del():
  if request.method == 'GET':
    id = request.args.get('id',0,type=int)
    if id:
      Article.query.filter_by(id=id).delete()
      db.session.commit()
      db.session.close()
      return fun.msg_json(1, '已删除')
  elif request.method == 'POST':
    ids = request.form.get('data','',type=str)
    idsjs = json.loads(ids)
    for i in idsjs:
      Article.query.filter_by(id=i).delete()
    db.session.commit()
    db.session.close()
    return fun.msg_json(1, '已删除')

@main.route('/article_title',endpoint='article_title',methods=['POST'])
@fun.is_login
def article_title():
  liststr = request.form.get('checkliststr','',type=str)
  exts = request.form.get('exts','',type=str)
  isexts = request.form.get('isexts',0,type=int)
  if liststr and exts:
    listarr = liststr.split(",")
    for i in listarr:
      arttitle = Article.query.filter_by(id=i).first()
      if isexts==0:
        arttitle.title = exts+arttitle.title
      else:
        arttitle.title = arttitle.title+exts
    db.session.commit()
    db.session.close()
    return fun.msg_json(1, '修改成功')
  return fun.msg_json(0, 'error')
@main.route('/category',endpoint='category')
@fun.is_login
def category():
  category = Arttype.query.all()
  count = Arttype.query.count()
  return render_template('article/category.html',category=category,count=count)

@main.route('/category_add',endpoint='category_add',methods=['GET', 'POST'])
@fun.is_login
def category_add():
  if request.method == 'GET':
    return render_template('article/category_add.html')
  elif request.method == 'POST':
    name = request.form['name']
    if len(name) > 0:
      try:
        arttype_db = Arttype(catname = name)
        res = db.session.add(arttype_db)
        db.session.commit()
        db.session.close()
        return fun.msg_json(1, '修改成功')
      except Exception as e:
        return fun.msg_json(0, 'error')
    return fun.msg_json(0, 'error')

@main.route('/category_del/<id>',endpoint='category_del',methods=['GET'])
@fun.is_login
def category_del(id):
  if request.method == 'GET':
    if id:
      db.session.query(Arttype).filter_by(id=id).delete()
      db.session.commit()
      db.session.close()
      return fun.msg_json(1, '删除成功')

@main.route('/article_release/<id>',endpoint='article_release',methods=['GET','POST'])
@fun.is_login
def article_release(id):
  if request.method == 'GET':
    sitelist = db.session.query(Release,Release.id,Release.sitename,Release.url).all()
    Art = db.session.query(Article,Article.title).filter_by(id=id).first()
    db.session.close()
    if sitelist:
      return render_template('article/article_release.html',row = sitelist,title = Art.title,id=id)
    return 'error'
  elif request.method == 'POST':
    try:
      if id:
        # time.sleep(2)
        siteid = request.form['siteid']
        sitetypeid = request.form['sitetypeid']
        if not siteid: return fun.msg_json(0, '请选择要发布的网站!')
        if not sitetypeid: return fun.msg_json(0, '请选择要发布的分类!')
        if siteid and sitetypeid:
          artdb = Article.query.filter_by(id=id).first()
          row = Release.query.filter_by(id=siteid).first()
          now_date ="{}{}{}".format(datetime.datetime.now().year,datetime.datetime.now().month,datetime.datetime.now().day)

          dede = dedecms(dedeurl=row.url+row.loginurl,session=resession,username=row.username,password=row.password,code=row.key,charset=row.charset)
          dede.set_cookie(json.loads(row.cookies))
          senddata = {}
          senddata['title'] = artdb.title
          senddata['typeid'] = sitetypeid
          senddata['body'] = artdb.content
          res,rescontent = dede.add(senddata)
          if res:
            if len(row.child)>0:
              aid = re.findall('archives_do.php\?aid=(\d+?)&dopost=editArchives',rescontent)
              for i in row.child:
                dede_child = dedecms(dedeurl=i.url + i.loginurl, session=resession, username=i.username,password=i.password,code=i.key, charset=i.charset)
                dede_child.set_cookie(json.loads(i.cookies))
                dede_child.makeChild(aid[0])
            artdb.status = 2
            if row.adddate != now_date:
              row.adddate = now_date
            adb = Addcountdb(rid=row.id,adddate=now_date)
            res = db.session.add(adb)
            db.session.commit()
            db.session.close()
            return fun.msg_json(1, '发布成功',id)
          else:
            return fun.msg_json(0, '发布失败')
      return fun.msg_json(0, '发布失败,参数错误')
    except Exception as e:
      print(e)
      return fun.msg_json(0, '发布失败'+str(e))


@main.route('/to_art_type/<id>',endpoint='to_art_type')
@fun.is_login
def to_art_type(id):
  if id:
    row = Release.query.filter_by(id=id).first()
    if row:
      dede = dedecms(dedeurl=row.url+row.loginurl,session=resession,username=row.username,password=row.password,code=row.key,charset=row.charset)
      dede.set_cookie(json.loads(row.cookies))
      ischeck = dede.check()
      if not ischeck:
        if row.key:
          islogin,cookie = dede.login(row.key)
          if islogin and cookie:
              row.cookies = cookie
              db.session.commit()
              db.session.close()
          else:
            return fun.msg_json(0, '该网站Cookie已失效，请登录！')
        else:
          return fun.msg_json(0, '该网站Cookie已失效，请登录！')

      artlist = dede.getTypelist()
      resjson = jsonify(artlist)
      return resjson
    return fun.msg_json(0, 'error')

def allowed_file(filename):
  return '.' in filename and \
         filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@main.route('/toupload',endpoint='toupload',methods=['POST'])
@fun.is_login
def toupload():
  if 'file' not in request.files:
    pass


@main.route('/txtimport',endpoint='txtimport',methods=['GET','POST'])
@fun.is_login
def txtimport():
  if request.method == 'GET':
    return render_template('article/txtimport.html')
  elif request.method == 'POST':
    file = request.files['file']
    title = file.readline().decode('gb2312',errors='ignore').strip()
    content = ''
    for line in file.readlines():
      line = line.decode('gb2312',errors='ignore').replace('\r','').replace('\n','')
      if line:
        content += fun.outhtml(line)
    art = Article(title=title,content=content)
    db.session.add(art)
    db.session.commit()
    db.session.close()
    return {'code':1,'title':title,'artid':art.id}

@main.route('/towyc/<id>',endpoint='towyc')
@fun.is_login
def towyc(id):
  try:
    if id:
      art = Article.query.filter_by(id=id).first()
      Wycobj = Wyc()
      stddd = Wycobj.toWyc(art.content)
      return render_template('article/article_wyc.html',row=art,newcon=stddd)      
    return fun.msg_json(0,'error2')
  except Exception as e:
    print(e)
    return fun.msg_json(0,'error1')


@main.route('/toupdateart/<id>',endpoint='toupdateart',methods=['POST'])
@fun.is_login
def toupdateart(id):
    content = request.form.get('content', '', type=str)
    ifg = request.form.get('ifg', 0, type=int)
    if content :
        arbdb = Article.query.filter_by(id=id).first()
        if arbdb:
            arbdb.content = content
            if ifg:
              arbdb.status_ifg = 2
            db.session.commit()
            db.session.close()
            return fun.msg_json(1,'成功')

    return fun.msg_json(0, 'error1')



@main.route('/ifagou_tosub/<id>',endpoint='ifagou_tosub')
@fun.is_login
def ifagou_tosub(id):
  row = Article.query.filter_by(id=id).first()
  if row:
    if not row.status_ifg:
        ifagouobj = ifagou()
        userid,secret = getTokey()
        if not userid:
            return fun.msg_json(0, '伪原创当天可用积分已用完！')
        ifagouobj.setkey(userid,secret)
        contenttmp = fun.filter_tags(row.content)
        result = ''
        temdatas = contenttmp.split("######")
        for i in temdatas:
          result = result + fun.outhtml(str(i))
        ifagou_res,ifagou_res_id = ifagouobj.tosubmit(row.title,result)
        if ifagou_res==1 and ifagou_res_id:
          row.status_ifg = 1
          row.ifg_id = ifagou_res_id
          row.ifg_userid = userid
          db.session.commit()
          db.session.close()
          return fun.msg_json(1, '提交成功')
        elif ifagou_res == 0:
          return fun.msg_json(0, userid+'账号当天可用积分已用完，请重新提交！')
        else:
          return fun.msg_json(0, '提交失败！')
    elif row.status_ifg == 1 and row.ifg_id:
        ifagouobj = ifagou()
        ifagouobj.setkey(row.ifg_userid)
        ifagou_data = ifagouobj.getdata(row.ifg_id)
        datayc = ifagou_data[0]
        if datayc['status'] == 0:
          return fun.msg_json(0, 'AI伪原创正在处理中...')
        elif datayc['status'] == 3 and str(datayc['docId']) == str(row.ifg_id):
          return fun.msg_json(2,'',{'old':row.content,'new':datayc['content']})
    elif row.status_ifg == 2:
          return fun.msg_json(0, '已经伪原创过，无需再次处理！')
  return fun.msg_json(0, 'error122')

@main.route('/ifagou_tosub_do/<id>',endpoint='ifagou_tosub_do')
@fun.is_login
def ifagou_tosub_do(id):
  try:
    if id:
      row = Article.query.filter_by(id=id).first()
      if row.status_ifg == 1 and row.ifg_id:
        ifagouobj = ifagou()
        ifagouobj.setkey(row.ifg_userid)
        ifagou_data = ifagouobj.getdata(row.ifg_id)
        datayc = ifagou_data[0]
        if datayc['status'] == 3 and str(datayc['docId']) == str(row.ifg_id):
          data_content = fun.replace_ifg(datayc['content'])
          return render_template('article/ifagouapi_wyc.html',row=row,newcon=data_content)  
    return fun.msg_json(0,'error2')
  except Exception as e:
    print(e)
    return fun.msg_json(0,'error1')

@main.route('/ifagouapi',endpoint='ifagouapi')
@fun.is_login
def ifagouapi():
  row = Ifgapi.query.all()
  count = len(row)
  return render_template("article/ifagouapi.html",row=row,count=count,getifgstatus=fun.getifgstatus)

@main.route('/ifagouapi_clear/',endpoint='ifagouapi_clear')
@fun.is_login
def ifagouapi_clear():
  db.session.query(Ifgapi).update({'statusdate':0})
  db.session.commit()
  db.session.close()
  return fun.msg_json(1, '1')

@main.route('/ifagouapi_add',endpoint='ifagouapi_add',methods=['GET','POST'])
@fun.is_login
def ifagouapi_add():
  if request.method == 'GET':
    row = Ifgapi.query.all()
    return render_template("article/ifagouapi_add.html",row=row)
  elif request.method == 'POST':
    userid = request.form['userid']
    secret = request.form['secret']
    if len(userid) > 0 and len(secret) > 0:
      try:
        Ifgapi_db = Ifgapi(userid = userid,secret=secret,status=0,statusdate=0)
        res = db.session.add(Ifgapi_db)
        db.session.commit()
        db.session.close()
        return fun.msg_json(1, '添加成功')
      except Exception as e:
        return fun.msg_json(0, 'error')
    return fun.msg_json(0, 'error')


@main.route('/ifagouapi_del/<id>',endpoint='ifagouapi_del',methods=['GET'])
@fun.is_login
def ifagouapi_del(id):
  if request.method == 'GET':
    if id:
      db.session.query(Ifgapi).filter_by(id=id).delete()
      db.session.commit()
      db.session.close()
      return fun.msg_json(1, '删除成功')

def getTokey():
  today = int(time.strftime("%Y%m%d", time.localtime()))
  res = Ifgapi.query.filter(Ifgapi.statusdate != today).first()
  if res:
    return res.userid,res.secret
  return False,False

